package com.ruoyi.user.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.check.CheckEmptyUtil;
import com.ruoyi.common.utils.login.LoginUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.user.domain.User;
import com.ruoyi.user.mapper.UserLabelMapper;
import com.ruoyi.user.mapper.UserMapper;
import com.ruoyi.user.service.IUserService;
import com.ruoyi.user.vo.DeleteUserLabeVo;
import com.ruoyi.user.vo.UserLabelName;
import com.ruoyi.user.vo.UserLoginOutVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 客户管理Controller
 *
 * @author ruoyi
 * @date 2025-04-10
 */
@RestController
@RequestMapping("/user/user")
public class UserController extends BaseController {
    @Autowired
    private IUserService userService;
    @Resource
    private LoginUtil loginUtil;
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserLabelMapper userLabelMapper;

    /**
     * 查询客户管理列表
     */
    @PreAuthorize("@ss.hasPermi('user:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(User user) {
        startPage();
        List<User> list = userService.selectUserList(user);

        return getDataTable(list);
    }

    /**
     * 导出客户管理列表
     */
    @PreAuthorize("@ss.hasPermi('user:user:export')")
    @Log(title = "客户管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, User user) {
        List<User> list = userService.selectUserList(user);
        ExcelUtil<User> util = new ExcelUtil<User>(User.class);
        util.exportExcel(response, list, "客户管理数据");
    }

    /**
     * 获取客户管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('user:user:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        User user = userService.selectUserById(id);
        user.setPlaceOrderCount(userMapper.selectUserPlaceOrderCount(id));
        BigDecimal bigDecimal = userMapper.selectConsume(id, 0);
        BigDecimal upgradeConsume = userMapper.selectUpgradeConsume(id, 0);
        BigDecimal totalConsume = bigDecimal;
        if (!CheckEmptyUtil.isEmpty(upgradeConsume)) {
            totalConsume = totalConsume.add(upgradeConsume);
        }
        BigDecimal bigDecimal1 = userMapper.selectConsume(id, 1);
        BigDecimal upgradeConsume1 = userMapper.selectUpgradeConsume(id, 1);
        BigDecimal monthConsume = bigDecimal1;
        if (!CheckEmptyUtil.isEmpty(upgradeConsume)) {
            monthConsume = bigDecimal1.add(upgradeConsume1);
        }

        BigDecimal totalhRefund = userMapper.selectRefund(id, 0);
        BigDecimal monthRefund = userMapper.selectRefund(id, 1);
        user.setTotalConsume(totalConsume);
        user.setMonthConsume(monthConsume);
        user.setTotalRefund(totalhRefund);
        user.setMonthRefund(monthRefund);

        String vipName = userMapper.selectVipName(id);
        user.setUserVipName(CheckEmptyUtil.isEmpty(vipName) ? "" : vipName);

        String labeList = userMapper.selectUserLabeList(id);
        List<UserLabelName> labelNameList = new ArrayList<>();
        if (!CheckEmptyUtil.isEmpty(labeList)) {
            for (String name : labeList.split(",")) {
                UserLabelName userLabelName = new UserLabelName();
                Long id1 = userLabelMapper.selectId(name);
                userLabelName.setId(id1);
                userLabelName.setName(name);
                labelNameList.add(userLabelName);
            }
        }
        user.setUserLabelName(labelNameList);


        return success(user);
    }

    /**
     * 新增客户管理
     */
    @PreAuthorize("@ss.hasPermi('user:user:add')")
    @Log(title = "客户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody User user) {
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改客户管理
     */
    @PreAuthorize("@ss.hasPermi('user:user:edit')")
    @Log(title = "客户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody User user) {
        return toAjax(userService.updateUser(user));
    }

    @PostMapping("deleteUserLabel")
    public AjaxResult deleteUserLabel(@RequestBody DeleteUserLabeVo deleteUserLabeVo) {
        return toAjax( userService.deleteUserLabel(deleteUserLabeVo));
    }

    /**
     * 删除客户管理
     */
    @PreAuthorize("@ss.hasPermi('user:user:remove')")
    @Log(title = "客户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(userService.deleteUserByIds(ids));
    }


    /**
     * 拉黑
     */
    @PreAuthorize("@ss.hasPermi('user:user:remove')")
    @Log(title = "客户管理", businessType = BusinessType.DELETE)
    @PostMapping("/userLoginOut")
    public AjaxResult userLoginOut(@RequestBody UserLoginOutVo requestVo) {
        loginUtil.userLoginOut(requestVo.getId());
        Integer updated = userMapper.updateIsDelete(requestVo.getId(), 1);
        return toAjax(updated);
    }


    /**
     * 解封
     */
    @PreAuthorize("@ss.hasPermi('user:user:remove')")
    @Log(title = "客户管理", businessType = BusinessType.DELETE)
    @PostMapping("/userUntieDisable")
    public AjaxResult userUntieDisable(@RequestBody UserLoginOutVo requestVo) {
        loginUtil.userUntieDisable(requestVo.getId());
        Integer updated = userMapper.updateIsDelete(requestVo.getId(), 0);
        return toAjax(updated);
    }
}
